package org.rslai.tcedit.dao.hibernate;

import java.util.List;
import org.rslai.tcedit.dao.CaseStateDao;
import org.rslai.tcedit.domain.CaseState;
import org.rslai.tcedit.domain.Page;
import org.rslai.tcedit.exception.ApplicationException;

/**
 * CaseStateDao的实现类
 * 
 * @author rslai
 * 
 * @spring.bean id="caseStateDao"
 */
public class CaseStateImpl extends GenericHibernateDao<CaseState> implements CaseStateDao {

	public CaseStateImpl() {
		super(CaseState.class);
	}

	/**
	 * 创建一个 CaseState 信息。覆盖 GenericHibernateDao 中的 create 方法。
	 * 
	 * @param caseState CaseState对象
	 */
	public void create(CaseState caseState) {
		CaseState tmpCaseState = (CaseState) queryForObject(
				"from CaseState as a where a.name=?",
				new Object[] { caseState.getName() }
		);
		if (tmpCaseState != null) {
			throw new ApplicationException("您输入的“测试用例编写状态名”已存在，请重新输入。");
		}

		// 设置 Sequence 为所有Sequence 字段的最大值+1
		int rowCount = (Integer)queryForObject(
				"select max(a.sequence) from CaseState as a",
				new Object[] {} );
		caseState.setSequence(rowCount + 1);
		
		hibernateTemplate.save(caseState);
	}
	
	/**
	 * 更新一个 CaseState 信息。覆盖 GenericHibernateDao 中的 update 方法。
	 * 
	 * @param caseState CaseState 对象
	 */
	public void update(CaseState caseState) {
		CaseState tmpCaseState = (CaseState) queryForObject(
				"from CaseState as a where a.name=? and a.id!=?",
				new Object[] { caseState.getName(), caseState.getId() }
		);
		if (tmpCaseState != null) {
			throw new ApplicationException("您输入的“测试用例编写状态名”已存在，请重新输入。");
		}

		hibernateTemplate.update(caseState);
	}

	private static final String QUERY_CASE_STATE_ALL_ASC = "from CaseState as a order by a.sequence";
	private static final String QUERY_CASE_STATE_ALL_DESC = "from CaseState as a order by a.sequence desc";

	@SuppressWarnings("unchecked")
	public List<CaseState> query(boolean asc) {
		return queryForList(
				asc ? QUERY_CASE_STATE_ALL_ASC : QUERY_CASE_STATE_ALL_DESC,
				null);
	}

    private static final String QUERY_CASE_STATE_ASC = "from CaseState as a where a.name LIKE ? order by a.sequence";
    private static final String QUERY_CASE_STATE_DESC = "from CaseState as a where a.name LIKE ? order by a.sequence desc";

    @SuppressWarnings("unchecked")
	public List<CaseState> query(Page page, String name, boolean asc) {
		return queryForList(
				"select count(*) from CaseState as a where a.name LIKE ?",
				asc ? QUERY_CASE_STATE_ASC : QUERY_CASE_STATE_DESC, 
				new Object[] { name },
				page
		);
	}

}
